import styles from './index.module.scss'
import Layout from '@c/layout'
import Image from '@c/image'
import cm from 'classnames'
import { isPureNumber, injectStructData, deleteScript } from '@/utils/utils'
import { getActorInfo, getCollectionFromActor } from '@/api/vod'
import shuffle from 'lodash-es/shuffle'
import { useEffect, useRef, useState } from 'react'
import dynamic from 'next/dynamic'
import { pcStore } from '@/store'
import { useRecoilValue } from 'recoil'

const AwardWork = dynamic(() => import('@c/award-work'))
const ActorWorkItem = dynamic(() => import('@c/actor-work-item'))
const ArrowSvg = dynamic(() => import('@c/svg/arrow'))

const formatStructData = actorInfo => {
  const { name, otherName: additionalName, birthDate, sex } = actorInfo
  const gender = sex == 2 ? '男' : sex == 1 ? '女' : '保密'
  let relatedTo = []
  try {
    const fams = actorInfo.familyMember.split('/')
    fams.forEach(item => {
      relatedTo.push({
        '@type': 'Person',
        name: item
      })
    })
  } catch (error) {}
  const data = {
    '@context': 'http://schema.org',
    '@type': 'Person',
    name,
    additionalName,
    award: actorInfo.awards || '',
    birthDate,
    birthPlace: {
      '@type': 'Place',
      address: actorInfo.birthAd
    },
    gender,
    jobTitle: actorInfo.profession,
    relatedTo,
    image: actorInfo.headPic,
    description: actorInfo.info
  }
  deleteScript('person')
  injectStructData(data, 'person')
}

const Index = props => {
  const { actorInfo, collections, bgColor } = props
  const isPC = useRecoilValue(pcStore)
  const textRef = useRef(null)
  const [expend, setExpend] = useState(true)
  const [canExpend, setCanExpend] = useState(false)
  useEffect(() => {
    formatStructData(actorInfo)
    const canExpended = textRef.current.scrollHeight > textRef.current.offsetHeight
    setCanExpend(canExpended)
    setExpend(canExpended)
    return () => {
      deleteScript('person')
      sessionStorage.setItem('lastPage', true)
    }
  }, [])
  return (
    <div className={cm(styles.person, styles.personPhone)}>
      <div className={styles.actorInfo} style={{ backgroundColor: bgColor }}>
        <div className={styles.actorBox}>
          <div className={styles.actorImg}>
            <Image src={actorInfo.headPic} alt="头像" />
          </div>
          <div className={styles['actor-info']}>
            <h1 className={styles.name}>{actorInfo.name}</h1>
            <p className={cm(styles.pPhone, 'hideWhenPc')}>
              <span>{actorInfo.sex === 1 ? '女' : '男'}</span>
              <span>{actorInfo.birthDate}</span>
              <span>{actorInfo.profession}</span>
            </p>
            <p className={cm(styles.p, 'hideWhenPhone')}>
              <span>性别：</span>
              <span>{actorInfo.sex === 1 ? '女' : '男'}</span>
            </p>
            <p className={cm(styles.p, 'hideWhenPhone')}>
              <span>生日：</span>
              <span>{actorInfo.birthDate || '-'}</span>
            </p>
            <p className={styles.p}>
              <span>出生地：</span>
              <span>{actorInfo.birthAd || '-'}</span>
            </p>
            <p className={styles.p}>
              <span>又名：</span>
              <span>{actorInfo.otherName || '-'}</span>
            </p>
            <p className={cm(styles.p, 'hideWhenPhone')}>
              <span>职业：</span>
              <span>{actorInfo.profession || '-'}</span>
            </p>
            <p className={styles.p}>
              <span>家庭成员：</span>
              <span>{actorInfo.familyMember || '-'}</span>
            </p>
            <p className={cm(styles.info, !expend ? styles.infoOpen : '')} ref={textRef}>
              {actorInfo.info || '暂无影人简介'}
            </p>
            {canExpend ? (
              <div className={styles.open} onClick={() => setExpend(!expend)}>
                <span>{expend ? '展开' : '收起'}</span>
                <ArrowSvg className={styles.img} width={12} fill="var(--theme-color)" />
              </div>
            ) : (
              <div className={styles.open}></div>
            )}
          </div>
        </div>
      </div>
      <Layout top={isPC ? -40 : 0}>
        {!!actorInfo.awards?.length && <AwardWork list={actorInfo.awards || []} />}
        {!!collections.length && <ActorWorkItem list={collections} />}
      </Layout>
    </div>
  )
}

export default Index

const colorArr = ['#22383a', '#222c3a', '#2b223a', '#3a2222']

export async function getServerSideProps({ params }) {
  const { id } = params
  if (!isPureNumber(id)) return { notFound: true }
  let layoutProps = {}
  const resArr = await Promise.all([getActorInfo(id, {}), getCollectionFromActor(id, {})])
  try {
    if (!resArr[0].data.id) {
      return { notFound: true }
    }
  } catch (error) {
    return { notFound: true }
  }

  const actorInfo = resArr[0].data
  try {
    layoutProps = {
      noSomeMetaInfo: false,
      title: `${actorInfo.name}人物介绍及相关影片 - 星视界`,
      desc: actorInfo.info || `${actorInfo.name}人物简介 - 星视界`,
      url: '/person'
    }
  } catch (error) {}
  return {
    props: {
      bgColor: shuffle(colorArr).pop(),
      layoutProps,
      actorInfo,
      collections: resArr[1]?.data?.actorCollections || []
    }
  }
}
